// pages/dativer2/dativer2.js
Page({
  _storeOptionObject: function(e){
    let t = e.detail.index
    if(t){
      this.data[t] = this.selectComponent("#"+t)
    }
  },

  _tapOptionItem: function(e){
    let index = this.data.a_dict[e.detail.index] /* 1 */
    if(this.data.type === "多选题"){
      if(e.detail.isActive){/* 添加 */
        if(this.data.user_answer.indexOf(index) === -1){
          this.data.user_answer.push(index)
        }
      }else{/* 删除 */
        for(let i = 0, l = this.data.user_answer.length; i < l; i++){
          if(this.data.user_answer[i] == index){
            this.data.user_answer.splice(i, 1)
            break
          }
        }
      }
    }else{
      if(this.data.user_answer.length != 0){
        let n = this.data.a_dict[this.data.user_answer[0]] /* "A" */
        this.data[n]._setType('noactive')
      }
      this.data.user_answer[0] = index
    }
  },
  /*显示题目*/
  _showQuestions: function(index=0){
    let t = this.data.questions[index]
    console.log("t=",t)
    let type = ""
    if(t.type == 1){ type = "判断题" }else if(t.type == 2){ type = "单选题" }else if(t.type == 3){ type = "多选题" }else{ type = "未知题型" }
    
    this.setData({
      nextButtonText: "确定",
      current: index+1,
      type: type,
      c_or_w: '',
      hint: t["hint"] || "",
      source: t["source"] || "",
      content: t.content,
      answer: t.answer,
      option_a: t["option_a"] || "",
      option_b: t["option_b"] || "",
      option_c: t["option_c"] || "",
      option_d: t["option_d"] || "",
      user_answer: [],
      analysis: t["analysis"] || '',
      showAnalysis: false,
      answerText: ''
    }, ()=>{this.data.start_time = Date.now()})
  },
  _nextQuestion: function(e){
    console.log("next e = ",e)
    
    let text = this.data.nextButtonText //确定 或 下一题
    let t = this.data.user_answer.sort()
    if(text == "确定"){
      this.data.total_time += Date.now() - this.data.start_time

      if(this.data.current == this.data.total){
        this.setData({showAnalysis: true, nextButtonText: "完成答题"})
      }else{
        this.setData({showAnalysis: true, nextButtonText: "下一题"})
      }
      
      if(this._isequal(this.data.answer.sort(), t)){//判断答案的
        this.data.correct += 1
        this.data.score += 1
        this.setData({c_or_w: 'c'})
      }else{
        this.setData({c_or_w: 'w'})
      }
      this._showCorrectAnswers()
    }else if(text == "下一题"){
      let t_dict = {}
      let t_array = this.data.user_answer.concat(this.data.answer)
      for(let i = 0, l = t_array.length; i < l; i++){
        let v = t_array[i]
        console.log("v=",v)
        if(!t_dict[v]){
          this.data[this.data.a_dict[v]]._setType('noactive')
          t_dict[v] = 1
        }
      }
      this._showQuestions(this.data.current)//显示下一题
    }else{
      wx.redirectTo({url: '../answerFinished/answerFinished?total=' + this.data.total +'&correct=' + this.data.correct + '&time=' + this.data.total_time + '&score=' + this.data.score})
    }
  },
  /*根据正确和错误答案更改用户选中的选项的样式*/
  _showCorrectAnswers: function(){
    let u_a = this.data.user_answer
    let c_a = this.data.answer.sort()
    let text = ''
    for(let i = 0, l = u_a.length; i < l; i++){
      let v = u_a[i]
      if(c_a.indexOf(v) == -1){
        this.data[this.data.a_dict[v]]._setType('wrong')
      }else{
        this.data[this.data.a_dict[v]]._setType('correct')
      }
    }
    for(let i = 0, l = c_a.length; i < l; i++){
      let v = this.data.a_dict[c_a[i]]
      console.log("v=",v)
      this.data[v]._setType('correct')
      if(v == 'F'){
        text += '错误 '
      }else if(v == 'T'){
        text += '正确 '
      }else{
        text += v + ' '
      }
    }
    console.log("text = ", text)
    this.setData({answerText: text})
  },

  _isequal: function (array1, array2) {
    if (!array2 || !array1) return false;
    if (array1.length != array2.length) return false;
    for (var i = 0, l = array1.length; i < l; i++) {
        if (array1[i] instanceof Array && array2[i] instanceof Array) {
            if (!array1[i].equals(array2[i]))
                return false;
        }
        else if (array1[i] != array2[i]) {
            return false;
        }
    }
    return true;
  },
  /**
   * 页面的初始数据
   */
  data: {
    isLoading: true,
    quizID: "0",
    start_time: 0,
    total_time: 0,
    questions: [],
    // questions: [{
    //   "qid": "79550af2607d09720f6d2b091c644a7f",
    //   "content": "“南陈北李，相约建党”是指1920年，(     )和(     )秘密相约筹建中国共产党。",
    //   "type": 2,
    //   "option_a": "陈望道  李  达",
    //   "option_b": "陈独秀  李大钊",
    //   "option_c": "陈  云  李克农",
    //   "option_d": "陈潭秋  李汉俊",
    //   "answer": [2],
    //   "analysis": "这里是解析"
    // },{
    //   "qid": "79550af2607d09720f6d2b091c644a7f",
    //   "content": "保密工作作为一门科学,有自身必须遵循的原则,包括最小化、（   ）原则。",
    //   "type": 3,
    //   "option_a": "全程化",
    //   "option_b": "精准化",
    //   "option_c": "自主化",
    //   "option_d": "法制化",
    //   "answer": [2,1,4,3]
    // },{
    //   "qid": "79550af2607d09720f6d2b091c644a7f",
    //   "content": "国家秘密和工作秘密、商业秘密、个人隐私之间存在重叠、交叉，有的信息可能既是国家秘密，又是工作秘密或者商业秘密。",
    //   "type": 1,
    //   "answer": [6],
    //   "hint": "正确，才怪。",
    //   "analysis": "该题为正确，才怪。"
    // }],
    nextButtonText: "确定",
    total: 0,
    c_or_w: '',
    correct: 0,
    current: 0,
    content: "",
    type: "",
    score: 0,
    source: undefined,
    hint: undefined,
    option_a: undefined,
    option_b: undefined,
    option_c: undefined,
    option_d: undefined,
    answer: [],
    user_answer: [],
    analysis: '',
    showAnalysis: false,
    answerText: '',
    a_dict: {"A":1, "B":2, "C":3, "D":4, "T":5, "F":6, 1:"A", 2:"B", 3:"C", 4:"D", 5:"T", 6:"F"}
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let id = options.id//接收id
    this.setData({quizID: id})
    console.log("从页面传递过来的id为", id)
    // //以下到return那一句（包含），用于本地调试
    // this.setData({total: this.data.questions.length, isLoading: false})
    // this._showQuestions()
    // return
    // //本地调试end
    wx.cloud.callFunction({
      name: 'getQuestions',
      data: {id: id}
    }).then(res => {
        let data = res.result
        if(!data){
          console.log('无数据')
        }else{
          this.setData({questions: this.data.questions.concat(data), total: data.length, isLoading: false}, this._showQuestions)
        }
      }
    ).catch(err => {
      console.log(err)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log("dativer2 onReady")
    this.data.start_time = Date.now() //number毫秒数
    console.log("start_time=",this.data.start_time)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})